package com.proj.hot.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.WindowManager;

import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 获取一些基本信息（mac,ip,像素分辨率，dp/sp与px的相互转换，dpi,versionName,versionCode,apkName）
 * Created by zangchenggang on 17/2/16.
 */
public class BaseInfoUtil {

    /**
     * 获取本机MAC地址
     *
     * @return
     */
    public static String getMacAddress() {
        String mac = null;
        try {
            String path = "sys/class/net/eth0/address";
            FileInputStream fis_name = new FileInputStream(path);
            byte[] buffer_name = new byte[8192];
            int byteCount_name = fis_name.read(buffer_name);
            if (byteCount_name > 0) {
                mac = new String(buffer_name, 0, byteCount_name, "utf-8");
            }
            if (mac == null) {
                fis_name.close();
                return "";
            }
            fis_name.close();
        } catch (Exception io) {
            io.printStackTrace();
            DebugUtil.i("BaseInfoUtil", "获取Mac失败");
        }

        if (mac == null) {
            return "";
        } else {
            return mac.trim();
        }
    }

    /**
     * 获取本机IP地址(IPv4地址，格式xx.xx.xx.xx)
     *
     * @return
     * @throws SocketException
     */
    public static String getIPAddress() {
        String tempAddress = "";
        String ipAddress = "";
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface intf = netInterfaces.nextElement();
                if (intf.getName().toLowerCase().equals("eth0")
                        || intf.getName().toLowerCase().equals("wlan0"))// 仅保留以太网和无线网的IP信息
                {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                            .hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            tempAddress = inetAddress.getHostAddress().toString();
                            if (!tempAddress.contains("::"))// 筛掉ipV6地址
                            {
                                ipAddress = tempAddress;
                            }
                        }
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            DebugUtil.i("BaseInfoUtil", "获取IP失败");
        }
        return ipAddress;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getWindowsWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        return width;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */
    public static int getWindowsHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }

    /**
     * 获取屏幕DPI
     *
     * @param activity
     * @return
     */
    public static int getWindowsDPI(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int dpi = metrics.densityDpi;
        return dpi;
    }

    /**
     * 根据电视的分辨率从 dp (设备独立像素)的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据电视的分辨率从 px(像素) 的单位 转成为 dp(设备独立像素)
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * sp转px
     *
     * @param context
     * @param
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px转sp
     *
     * @param
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    /**
     * 当前APK版本
     *
     * @returname
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String versionName = packInfo.versionName;
        String apkName = packInfo.applicationInfo.loadLabel(packageManager).toString();
        //return apkName + " 版本：" + versionName;
        return versionName;
    }

    /**
     * version
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int versionCode = packInfo.versionCode;
        String apkName = packInfo.applicationInfo.loadLabel(packageManager).toString();
        return versionCode;
    }

    /**
     * 根据应用包名获取应用名
     *
     * @param context
     * @param appPackageName
     * @return 返回应用名，不存在返回null
     */
    public static String getAppName(Context context, String appPackageName) {
        PackageManager pm = context.getPackageManager();
        String appName = null;
        try {
            appName = pm.getApplicationInfo(appPackageName, 0).loadLabel(pm)
                    .toString();
            return appName;
        } catch (Exception e) {//不存在
            return appName;//返回null
        }
    }

    /**
     * 根据包名获取版本号
     *
     * @param context
     * @param
     * @return
     * @throws Exception
     */
    public static String getVersionName(Context context, String packageName) {
        // TODO Auto-generated method stub
        PackageManager pm = context.getPackageManager();
        int flags = 0;
        PackageInfo packageInfo;
        String versionName = null;
        try {
            packageInfo = pm.getPackageInfo(packageName, flags);
            versionName = packageInfo.versionName;//版本名
            int versioncode = packageInfo.versionCode;//版本号
            return versionName;
        } catch (Exception e) {
            return versionName;//不存在返回null
        }
    }
}
